package com.glwan.fixedassetapp.ui.home.Activity;

import android.app.Activity;
import android.content.ContentValues;
import android.database.Cursor;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import com.glwan.fixedassetapp.Adapter.ListableAdapter;
import com.glwan.fixedassetapp.R;
import com.glwan.fixedassetapp.common.DatabaseConstant;
import com.glwan.fixedassetapp.components.SelectView;
import com.glwan.fixedassetapp.handler.ReaderResponseInterfaces;
import com.glwan.fixedassetapp.helper.KeyCodeReceiver;
import com.glwan.fixedassetapp.helper.RFIDDeviceInterface;
import com.glwan.fixedassetapp.model.RFIDTagData;
import com.glwan.fixedassetapp.ui.home.locateTag.LocateTagActivity;
import com.glwan.fixedassetapp.utils.CommonUtil;
import com.glwan.fixedassetapp.utils.DatabaseUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


public class OfflineInventoryActivity extends AppCompatActivity implements ReaderResponseInterfaces.ResponseStatusHandler, ReaderResponseInterfaces.ResponseTagHandler, ReaderResponseInterfaces.ResponseKeyEventHandler {

    RFIDDeviceInterface rfidDeviceInterface;
    KeyCodeReceiver keyCodeReceiver;
    Map<String, Map<String, Object>> inventoryMap = new HashMap<>();
    List<String> existData = new ArrayList<>();
    List<Map<String, Object>> insertInventoryMapList = new ArrayList<>();
    List<Map<String, Object>> insertInventoryMapListCache = new ArrayList<>();
    private List<Map<String, Object>> parentList = new ArrayList<>();
    private Map<String, Integer> groupTextViewMap = new HashMap<>();
    private ListView listView;
    private ListableAdapter listableAdapter;
    private Button btScanning;
    private SelectView selectView;
    Handler handler = new Handler(message -> {
        insertInventoryHandle();
        return false;
    });

    private Activity getActivity() {
        return this;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.scanning_layout_1);
        Toolbar toolbar = findViewById(R.id.moreToolbar);
        setSupportActionBar(toolbar);

        setTitle(getString(R.string.inventoryScanning));

        ActionBar actionBar = getSupportActionBar();
        if (actionBar != null) {
            actionBar.setHomeButtonEnabled(true);
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        btScanning = findViewById(R.id.btScanning);

        rfidDeviceInterface = RFIDDeviceInterface.getInstance(Build.BRAND, this);
        if (rfidDeviceInterface != null && !rfidDeviceInterface.isConnected()) {
            connectReader();
        }

        btScanning.setOnClickListener(view -> {
            inventory();
        });

        Button btConfirmUpload = findViewById(R.id.btConfirmUpload);
        btConfirmUpload.setVisibility(View.GONE);
        initCondition();

        initData();

    }

    private void connectReader() {
        Log.i("BRAND", Build.BRAND);
        Handler handler = new Handler();
        handler.postDelayed(() -> {
            if (rfidDeviceInterface != null) {
                rfidDeviceInterface.connect();
            } else {
                CommonUtil.toastShow(getActivity(), "当前设备不支持RFID", CommonUtil.ERROR, true);
            }
        }, 0);
    }

    /**
     * 初始化筛选条件的值
     */
    private void initCondition() {
        List<String> spinnerValueList = new ArrayList<>();

        String[] columnNames = new String[]{"PlaceOfPreservation"};

        Cursor cursor = DatabaseUtil.queryDistinctSQL(DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, columnNames, null, null);

        while (cursor.moveToNext()) {
            spinnerValueList.add(cursor.getString(0));
        }

        selectView = findViewById(R.id.selectView);
        selectView.setAdapter(new ArrayAdapter<>(
                getActivity(),
                R.layout.support_simple_spinner_dropdown_item,
                spinnerValueList
        ));
    }

    /**
     * 初始化数据
     */
    private void initData() {
        groupTextViewMap.put("sortNo", R.id.sortNo);
        groupTextViewMap.put("AssetName", R.id.fdYzCardName);
        groupTextViewMap.put("SerialNumber", R.id.fdId);
        groupTextViewMap.put("InventoryStatus", R.id.status);

        listView = findViewById(R.id.scanList);

        listableAdapter = new ListableAdapter(
                getActivity(),
                parentList,
                groupTextViewMap,
                R.layout.offline_inventory_item);
        listView.setAdapter(listableAdapter);

        listView.setOnItemLongClickListener((adapterView, view, i, l) -> {
            Map<String, Object> map = new HashMap<>();
            Map<String, Object> item = (Map<String, Object>) listableAdapter.getItem(i);
            map.put("tagPatternValue", item.get("SerialNumber").toString());
            CommonUtil.startActivity(getApplicationContext(), LocateTagActivity.class, map, true);
            return true;
        });
        queryData();
    }

    /**
     * 加载数据库数据
     */
    private void queryData() {
        //查询结果
        String[] columnNames = new String[]{"SerialNumber", "AssetName", "PlaceOfPreservation"};
        Cursor cursor = DatabaseUtil.querySQL(DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, columnNames, null, null);
        while (cursor.moveToNext()) {
            Map<String, Object> map = new HashMap<>();

            for (String s : columnNames) {
                int columnIndex = cursor.getColumnIndex(s);
                if (columnIndex >= 0) {
                    map.put(s, cursor.getString(columnIndex));
                }
            }
            int serialNumber = cursor.getColumnIndex("SerialNumber");
            if (serialNumber >= 0) {
                inventoryMap.put(cursor.getString(serialNumber), map);
            }
        }
        //parentList.addAll(inventoryMap.values());
    }

    //返回主界面
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == android.R.id.home) {
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    /**
     * RFID数据读回来的处理
     *
     * @param data
     */
    @Override
    public void handleResponse(RFIDTagData data) {
        String epc = data.getEpc();
        //不存在处理
        if (!existData.contains(epc)) {
            Map<String, Object> map = inventoryMap.get(epc);
            if (map != null) {
                String selectedItem = selectView.getSelectTextValue();
                if (selectedItem.isEmpty() || "null".equals(selectedItem)) {
                    map.put("InventoryStatus", "已盘");
                } else {
                    if (Objects.equals(map.getOrDefault("PlaceOfPreservation", ""), selectedItem)) {
                        map.put("InventoryStatus", "已盘");
                    } else {
                        map.put("InventoryStatus", "位置错误（盘点地点：" + selectedItem + "）");       // 2023-08-17，新增位置错误地点
                    }
                }
                parentList.add(map);
                Log.i("handleResponse", map.toString());
                existData.add(epc);
                runOnUiThread(() -> {
                    listableAdapter.notifyDataSetChanged();
                    insertInventoryMapList.add(map);

                    if (insertInventoryMapList.size() >= 100) {
                        Log.i("handleResponse", "每100条处理一次");
                        handler.sendEmptyMessage(0);
                    }

                });
            }
        }
    }

    //插入数据库处理
    private void insertInventoryHandle() {

        //加入缓存中
        insertInventoryMapListCache.addAll(insertInventoryMapList);
        insertInventoryMapList.clear();

        if (!insertInventoryMapListCache.isEmpty()) {
            //已盘条目的List
            List<String> countedIdList = new ArrayList<>();

            //异常盘点条目的List
            List<String> errorCountedIdList = new ArrayList<>();

            //盘点到的数据放入insertInventoryMapCache
            for (Map<String, Object> map : insertInventoryMapListCache) {

                String status = String.valueOf(map.get("InventoryStatus"));

                if ("已盘".equals(status)) {
                    countedIdList.add(String.valueOf(map.get("SerialNumber")));
                } else {
                    errorCountedIdList.add(String.valueOf(map.get("SerialNumber")));
                }

            }

            if (!countedIdList.isEmpty()) {
                ContentValues contentValues = new ContentValues();
                contentValues.put("InventoryStatus", "已盘点");
                contentValues.put("REASON", "");
                updateSqlHandle(countedIdList, contentValues);
            }
            if (!errorCountedIdList.isEmpty()) {
                String selectedItem = String.valueOf(selectView.getSelectTextValue());
                ContentValues contentValues = new ContentValues();
                contentValues.put("InventoryStatus", "异常盘点");
                contentValues.put("REASON", "位置错误（盘点地点：" + selectedItem + "）");
                updateSqlHandle(errorCountedIdList, contentValues);
            }

        }

        insertInventoryMapListCache.clear();

    }

    /**
     * 更新语句处理
     *
     * @param list          list
     * @param contentValues contentValues
     */
    private void updateSqlHandle(List<String> list, ContentValues contentValues) {
        int size = list.size();
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("(");
        for (int i = 0; i < size; i++) {
            String s = list.get(i);
            stringBuilder.append("'").append(s).append("'");
            if (!(i == size - 1)) {
                stringBuilder.append(",");
            }
        }
        stringBuilder.append(")");
        Log.i("insertInventoryHandle", "更新任务条目" + stringBuilder.toString() + "状态");

        int i = DatabaseUtil.updateData(DatabaseConstant.OFFLINE_INVENTORY_TASK_ITEM, contentValues, " SerialNumber IN " + stringBuilder.toString(), null);
        Log.i("更新成功条数", String.valueOf(i));
    }

    /**
     * 扳机按键返回处理事件
     */
    @Override
    public void handleResponse() {
        inventory();
    }

    private void inventory() {
        if (getString(R.string.startScanning).equals(btScanning.getText().toString())) {
            btScanning.setText(getString(R.string.stopScanning));
            rfidDeviceInterface.changeInventoryMode(0, null);
            rfidDeviceInterface.startInventory();
        } else {
            btScanning.setText(getString(R.string.startScanning));
            rfidDeviceInterface.stopInventory();
            handler.sendEmptyMessage(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        keyCodeReceiver = KeyCodeReceiver.getInstance(this);
        keyCodeReceiver.registerKeyCodeReceiver();
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (rfidDeviceInterface != null)
            rfidDeviceInterface.stopInventory();
        if (keyCodeReceiver != null)
            keyCodeReceiver.unregisterReceiver();
        btScanning.setText(getString(R.string.startScanning));
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void handleStatusResponse(boolean open) {
        if (open) {
            rfidDeviceInterface.changeInventoryMode(0, null);
        } else {
            handler.sendEmptyMessage(0);
        }
    }

}

